package com.gc.notify.message;

import com.gc.notify.GovcarObserver;
import com.gc.notify.GovcarSubject;
import com.gc.frontend.service.SettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 瑱彬 on 2015/4/30.
 */
@Component("messageSubject")
@Scope("singleton")
public class MessageSubject implements GovcarSubject {
    private List<GovcarObserver> observers;
    protected Map<String, Object> messageEntity = new HashMap<>();

    @Autowired
    private SettingService settingService;

    @Resource(name = "notifyObserver")
    private GovcarObserver notifyObserver;
    @Resource(name = "emailObserver")
    private GovcarObserver emailObserver;
    @Resource(name = "sMSObserver")
    private GovcarObserver smsObserver;

    @Override
    public void attach(List<GovcarObserver> observers) {
        if (this.observers == null) {
            this.observers = new ArrayList<>();
        }
        this.observers.addAll(observers);
    }

    @Override
    public void detach(List<GovcarObserver> observers) {
        if (this.observers == null) {
            this.observers = new ArrayList<>();
        } else {
            this.observers.removeAll(observers);
        }
    }

    @Override
    public void notifyObserver() {
        getObserver();
        for (GovcarObserver observer : observers) {
            observer.update(messageEntity);
        }
    }

    @Override
    public void getObserver() {
        Map<String, String> settings = settingService.getMaps();
        observers = new ArrayList<>();
        if ("true".equals(settings.get("notify_enable"))) {
            observers.add(notifyObserver);
        }
        if ("true".equals(settings.get("sms_enable"))) {
            observers.add(smsObserver);
        }
        if ("true".equals(settings.get("email_enable"))) {
            observers.add(emailObserver);
        }
    }

    @Override
    public void setMessage(Map<String, Object> message) {
        this.messageEntity = message;
    }
}
